<?php

/**
 *
 * @copyright (c) 2012 University of Geneva
 * @license GNU General Public License - http://www.gnu.org/copyleft/gpl.html
 * @author Laurent Opprecht <laurent@opprecht.info>
 */
define('INTERNAL', 1);
define('MENUITEM', 'content/files');
define('SECTION_PLUGINTYPE', 'artefact');
define('SECTION_PLUGINNAME', 'connect');

require(dirname(dirname(dirname(__FILE__))) . '/init.php');
safe_require('artefact', 'connect');
safe_require('artefact', 'file');
require_once __DIR__ . '/lib/import_archive.class.php';

define('TITLE', PluginArtefactConnect::get_string('upload'));

$url = isset($_GET['url']) ? $_GET['url'] : '';
$extract = isset($_GET['extract']) ? $_GET['extract'] : false;
$goto = isset($_GET['goto']) ? $_GET['goto'] : '/artefact/file/';

$form = array(
    'name' => 'http_upload',
    'method' => 'post',
    'plugintype' => 'artefact',
    'pluginname' => 'connect',
    'configdirs' => array(get_config('libroot') . 'form/', get_config('docroot') . 'artefact/file/form/'),
    'elements' => array(
        'url' => array(
            'type' => 'text',
            'title' => PluginArtefactConnect::get_string('url'),
            'defaultvalue' => $url,
            'size' => 50
        ),
        'extract' => array(
            'type' => 'hidden',
            'value' => $extract,
        ),
        'goto' => array(
            'type' => 'hidden',
            'value' => $goto,
        ),
        'submit' => array(
            'type' => 'submitcancel',
            'value' => array(get_string('save'), get_string('cancel')))
    ),
);

$form = pieform($form);
$smarty = smarty();
$smarty->assign('PAGEHEADING', TITLE);
$smarty->assign('form', $form);
$smarty->display('artefact:connect:upload.tpl');

function http_upload_submit(Pieform $form, $values)
{
    global $USER;

    $url = $values['url'];
    $extract = $values['extract'];
    $goto = $values['goto'];
    $goto = ltrim($goto, '/');
    $goto = '/' . $goto;

    $request = Curl::get($url, array(CURLOPT_HEADER => true));
    $request->execute();

    $http_code = $request->info('http_code');
    $success = 200 <= $http_code && $http_code <= 299 && $request->error_no() == 0;
    if (!$success) {
        Session::singleton()->add_error_msg(PluginArtefactConnect::get_string('transmissionfailed'));
        redirect($goto);
    }

    $content = $request->content();
    list($headers, $body) = explode("\r\n\r\n", $content, 2);

    //parse headers
    $items = explode("\r\n", $headers);
    $headers = array();
    foreach ($items as $item) {
        $parts = explode(':', $item);
        if (count($parts) == 2) {
            $key = $parts[0];
            $value = $parts[1];
            $headers[$key] = $value;
        } else {
            $headers[] = $item;
        }
    }

    //extract file name and content type
    $type = isset($headers['Content-Type']) ? $headers['Content-Type'] : '';
    $name = isset($headers['Content-Disposition']) ? $headers['Content-Disposition'] : '';
    $items = explode(';', $name);
    foreach ($items as $item) {
        if (strpos($item, 'filename') !== false) {
            list($key, $name) = explode('=', $item);
            break;
        }
    }

    $temp = get_config('dataroot') . '/temp/' . md5(uniqid());
    $temp .= is_zip($type) ? '.zip' : '';
    file_put_contents($temp, $body);

    if ($extract && is_zip($type)) {
        try {
            $import = new ImportArchive($temp);
            $result = $import->import();
        } catch (QuotaExceededException $e) {
            Session::singleton()->add_error_msg(PluginArtefactConnect::get_string('transmissionfailedquotatoolow'));
        } catch (Exception $e) {
            Session::singleton()->add_error_msg($e->getMessage());
        }
        if ($result) {
            Session::singleton()->add_ok_msg(PluginArtefactConnect::get_string('transmissioncomplete'));
        }
        unlink($temp);
        redirect($goto);
    }

    $data = (object) array();
    $data->owner = $USER->get('id');
    $data->title = $name;
    $data->filetype = $type;

    try {
        $newid = 0;
        $newid = ArtefactTypeFile::save_file($temp, $data, $USER, true);
    } catch (QuotaExceededException $e) {
        Session::singleton()->add_error_msg(PluginArtefactConnect::get_string('transmissionquotatoolow'));
    } catch (Exception $e) {
        Session::singleton()->add_error_msg($e->getMessage());
    }

    if ($newid) {
        Session::singleton()->add_ok_msg(PluginArtefactConnect::get_string('transmissioncomplete'));
    } else {
        Session::singleton()->add_error_msg(PluginArtefactConnect::get_string('transmissionfailed'));
    }
    unlink($temp);
    redirect($goto);
}

function http_upload_validate(Pieform $form, $values)
{
    return true;
}

/**
 * Returns true if the mimetype is a zip. False otherwise.
 * 
 * @param string $mime_type
 * @return boolean 
 */
function is_zip($mime_type)
{
    $mimetype = strtolower($mime_type);
    $parts = explode('/', $mime_type);
    if (count($parts) != 2) {
        return false;
    }
    $subtype = end($parts);
    return strpos($subtype, 'zip') !== false;
}
